package moltencore.game.collision;

import moltencore.game.bubble.AbstractBubble;
import spark.math.Vector2;
import moltencore.game.bubble.Bubble;

public class HorizontalLine implements ICollidable {
	private static final int COLLISION_ACCURACY = 5;

	private boolean sticky;
	private float yPosition;

	public HorizontalLine(float yPosition, boolean sticky) {
		this.yPosition = yPosition;
		this.sticky = sticky;
	}

	@Override
	public Vector2 collisionPoint(AbstractBubble bubble, Vector2 movement) {
		Vector2 newPosition = Vector2.add(bubble.getPosition(), movement);
		if(!collides(newPosition, Bubble.COLLISION_RADIUS)) {
			return null;
		}
		if(movement.y < 0) {
			newPosition.y = yPosition + Bubble.COLLISION_RADIUS;
		}
		else {
			newPosition.y = yPosition - Bubble.COLLISION_RADIUS;
		}
		return newPosition;
	}

	@Override
	public boolean collides(AbstractBubble bubble, Vector2 movement) {
		Vector2 newPosition = (movement == null) ? bubble.getPosition() : Vector2.add(bubble.getPosition(), movement);
		return collides(newPosition, Bubble.COLLISION_RADIUS);
	}

	private boolean collides(Vector2 circlePosition, float circleRadius) {
		float circleY = circlePosition.y;
		//fix the y coordinate of the bubble so that it is above
		if(circleY < yPosition) {
			circleY += 2 * (yPosition - circleY);
		}
		//if the bottom edge of the bubble is below of this line there is a collision
		return (circleY - circleRadius) < yPosition;
	}

	@Override
	public boolean isSticky() {
		return sticky;
	}

	@Override
	public boolean isPartOfWorld() {
		return true;
	}

	@Override
	public void collisionResponse(AbstractBubble bubble) {
		// if this collidable is sticky the bubble will stick to it and not move
		if(isSticky()) {
			bubble.getVelocity().x = 0;
			bubble.getVelocity().y = 0;
		}
		// else the bubble is reflected
		else {
			bubble.getVelocity().y *= -1;
		}
	}

	public float getYPosition() {
		return yPosition;
	}
}